import fs from 'node:fs';
import path from 'node:path';
import viteCommonReactConfig from '../common.react.config';
import viteReactConfig from './react.config';

async function serve() {
  const vite = (await import('vite')).default;

  const configPath = path.join(process.cwd(), './vite.config.ts');
  let overrides = {};

  if (fs.existsSync(configPath)) {
    const configFile = await vite.loadConfigFromFile(
      { command: 'serve', mode: 'development' },
      configPath,
    );

    overrides = configFile?.config || {};
  }

  const defaultConfig = vite.mergeConfig(
    await viteCommonReactConfig(),
    await viteReactConfig(),
  );
  const config = vite.mergeConfig(defaultConfig, overrides);
  const server = await vite.createServer(config);
  await server.listen();
  server.printUrls();
  server.bindCLIShortcuts({ print: true });
}
export default serve;
